package com.tedu.ivos.dictoption.service.impl;

import com.tedu.ivos.base.exception.ServiceException;
import com.tedu.ivos.base.response.StatusCode;
import com.tedu.ivos.dict.mapper.DictMapper;
import com.tedu.ivos.dict.pojo.dto.DictQuery;
import com.tedu.ivos.dict.pojo.entity.Dict;
import com.tedu.ivos.dict.pojo.vo.DictVO;
import com.tedu.ivos.dictoption.mapper.DictOptionMapper;
import com.tedu.ivos.dictoption.pojo.dto.DictOptionQuery;
import com.tedu.ivos.dictoption.pojo.dto.DictOptionSaveParam;
import com.tedu.ivos.dictoption.pojo.entity.DictOption;
import com.tedu.ivos.dictoption.pojo.vo.DictOptionVO;
import com.tedu.ivos.dictoption.service.IDictOptionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class DictOptionServiceImpl implements IDictOptionService {
    @Autowired
    private DictOptionMapper dictOptionMapper;
    @Autowired
    DictMapper dictMapper;

    @Override
    public List<DictOptionVO> select(DictOptionQuery dictOptionQuery) {
        log.debug("查询字典项业务，参数：{}",dictOptionQuery);
        return dictOptionMapper.select(dictOptionQuery);
    }

    @Override
    public void save(DictOptionSaveParam dictOptionSaveParam) {
        log.debug("保存字典项业务，参数：{}",dictOptionSaveParam);
        DictOption dictOption = new DictOption();
        BeanUtils.copyProperties(dictOptionSaveParam,dictOption);
        if(dictOption.getId()==null){
            log.debug("新增字典项业务，参数：{}",dictOptionSaveParam);
            dictOption.setCreateTime(new Date());
            dictOptionMapper.insert(dictOption);
        }else{
            log.debug("修改字典项业务，参数：{}",dictOptionSaveParam);
            dictOption.setUpdateTime(new Date());
            dictOptionMapper.update(dictOption);
        }
    }

    @Override
    public void delete(Long id) {
        log.debug("删除字典项业务，参数：{}",id);
        dictOptionMapper.delete(id);
    }

    @Override
    public List<DictOptionVO> selectDictOptionByCode(String code) {
        log.debug("根据字典code查询字典项业务，参数：{}",code);
        //需要先判断该字典是否存在，如果存在，再查询该字典下的字典项
        DictQuery dictQuery = new DictQuery();
        dictQuery.setCode(code);
        List<DictVO> dictVOList = dictMapper.select(dictQuery);
        if(dictVOList!=null&&dictVOList.size()>0){
            DictVO dictVO = dictVOList.get(0);
            DictOptionQuery dictOptionQuery = new DictOptionQuery();
            dictOptionQuery.setDictId(dictVO.getId());
            List<DictOptionVO> dictOptionVOList = dictOptionMapper.select(dictOptionQuery);
            return dictOptionVOList;
        }else{
            throw new ServiceException(StatusCode.DATA_UNEXISTS);
        }

    }
}
